<!--
 * @Author: your name
 * @Date: 2020-02-17 10:19:07
 * @LastEditTime: 2020-03-18 11:18:05
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \boot_vue\src\App.vue
 -->
<template>
  <div class="custom-video-progress" @click="onProgressClick">
    <!-- <el-progress ref="progress" :percentage="currentPercent" :show-text="false"></el-progress> -->
    <div ref="progress" class="el-progress-bar__outer" style="height: 12px;"><div ref="progress-inner" class="el-progress-bar__inner"><!----></div></div>
  </div>
</template>

<script>
import { dateFormat } from '@/utils'
export default {
  props: {
    date: {
      type: Array
    },
    // 初始化数据，当进度条被点击时会作为参数传递到事件
    data: {
      type: Object
    }
  },
  data () {
    return {
      preSecond: 0,
      totalSecond: 0,
      currentPercent: 0,
      currentProgressWidth: 0 // 就相当于当前的进度
    }
  },
  mounted () {
    this.initDate()
  },
  methods: {
    initDate () {
      this.progress = this.$refs['progress']
      this.progressInner = this.$refs['progress-inner']
      let startDate = this.date ? this.date[0] : 0
      let endDate = this.date ? this.date[1] : 0
      this.startTime = new Date(startDate).getTime()
      this.endTime = new Date(endDate).getTime()
      this.timestamp = this.endTime - this.startTime // 记录间隔时间差
      // 一开始初始化restSecond为总时间
      this.restSecond = this.totalSecond = (this.endTime - this.startTime) / 1000 // 转为秒
      this.progressTotalWidth = this.progress.clientWidth
    },
    resetProgress () {
      this.preSecond = 0
      // this.currentPercent = 0
      // 删除animation动画，否则下面设置的width不生效
      // this.deleteAnimationFrameRule(this.data.containerId)
      this.currentProgressWidth = 0
      this.progressInner.style.animation = 'none'
      this.progressInner.style.width = '0px'
    },
    resetPresecond () {
      this.preSecond = 0
    },
    increaseSecond (second) {
      let currentSecond = second - this.preSecond
      // 在当前的进度下往上加
      this.currentPercent = Math.min(100, this.numberToPercent(currentSecond / this.totalSecond) + this.currentPercent)
      this.preSecond = second
    },
    setSecond (second) {
      this.currentPercent = this.numberToPercent(second / this.totalSecond)
    },
    setPercentage (percent) {
      let width = percent * this.progressTotalWidth
      this.setPercentByWidth(width)
    },
    setPercentByWidth (width) {
      this.progressInner.style.animation = 'none'
      let percent = width / this.progressTotalWidth
      this.restSecond = this.totalSecond - (this.totalSecond * percent)
      this.currentProgressWidth = this.progressTotalWidth * percent
      // this.playProgressAnimation(this.currentProgressWidth, this.restSecond)
      this.progressInner.style.width = `${this.currentProgressWidth}px`
    },
    setPercentByWidthAndPlay (width) {
      this.setPercentByWidth(width)
      this.playProgressAnimation({ animationName: this.animationName, isIncrease: true })
    },
    onProgressClick (e) {
      // 点击进度条先清除animation属性
      // 删除animation动画
      // this.deleteAnimationFrameRule(this.data.containerId)
      this.progressInner.style.animation = 'none'
      let percent = e.offsetX / this.progressTotalWidth
      this.restSecond = this.totalSecond - (this.totalSecond * percent)
      this.currentProgressWidth = this.progressTotalWidth * percent
      // this.playProgressAnimation(this.currentProgressWidth, this.restSecond)
      this.progressInner.style.width = `${this.currentProgressWidth}px`
      let startTime = Math.floor(this.startTime + (percent * this.timestamp))
      let data = {
        ...this.data,
        startTime: dateFormat('YYYY-mm-dd HH:MM:SS', new Date(startTime)),
        endTime: dateFormat('YYYY-mm-dd HH:MM:SS', new Date(this.endTime))
      }
      this.$emit('onProgressClick', data)
    },
    stopProgressAnimation () {
      this.progressInner.style.animationPlayState = 'paused'
    },
    playProgressAnimation (options = { animationName: 'playProgress', isIncrease: false }) {
      // this.animationName供后续其他方法调用
      this.animationName = options.animationName
      if (options.isReStart) {
        // 当是重新播放时会触发两次start事件，也就是会再次执行options.isIncrease为true的插入代码，所以需要先删除一个
        this.progressInner.style.animationPlayState = 'running'
        return
      }
      this.deleteAnimationFrameRule(options.animationName)
      if (options.isIncrease) {
        document.styleSheets[0].insertRule(`@keyframes ${options.animationName} {
               0%{ width: ${this.currentProgressWidth}px; }
               100%{ width: ${this.progressTotalWidth}px; }`, 0)
        this.progressInner.style.animation = `${options.animationName} ${this.restSecond}s linear forwards`
        return
      }
      if (options.width && options.second) {
        document.styleSheets[0].insertRule(`@keyframes ${options.animationName} {
               0%{ width: ${options.width}px; }
               100%{ width: ${this.progressTotalWidth}px; }`, 0)
        this.progressInner.style.animation = `${options.animationName} ${options.second}s linear forwards`
      }
    },
    deleteRule (num = 0, index = 0) {
      let sheet = document.styleSheets[num]
      if (typeof sheet.deleteRule !== 'undefined') { // W3C
        sheet.deleteRule(index)
      } else if (typeof sheet.removeRule !== 'undefined') { // IE
        sheet.removeRule(index)
      }
    },
    deleteAnimationFrameRule (animationName) {
      let sheet = document.styleSheets[0]
      let cssRules = sheet.cssRules
      let keys = Object.keys(cssRules)
      keys.map((key, index) => {
        if (cssRules[key] && cssRules[key].name && cssRules[key].name === animationName) {
          // console.log(animationName)
          if (typeof sheet.deleteRule !== 'undefined') { // W3C
            sheet.deleteRule(index)
          } else if (typeof sheet.removeRule !== 'undefined') { // IE
            sheet.removeRule(index)
          }
        }
      })
    },
    getCssProperty (el, property) {
      let cssTable = document.defaultView.getComputedStyle(el)
      return cssTable ? cssTable[property] : ''
    },
    getCurrentWidth () {
      return this.progressInner.clientWidth
    },
    getCurrentPercentage () {
      return this.progressInner.clientWidth / this.progressTotalWidth
    },
    numFormat (percentage) {
      let second = Math.floor(this.percentToNumber(percentage) * this.totalSecond)
      let minute = Math.floor(second / 60)
      second = second % 60
      return `${minute} ：${second}`
    },
    // 小数转百分比， 如0.98转为98
    numberToPercent (num) {
      return num * 100
    },
    // 百分百转小数， 如98转为0.98
    percentToNumber (percent) {
      return percent / 100
    }
  },
  watch: {
    currentPercent (newV, oldV) {
      // console.log(newV)
    },
    date: { // 深度监听，可监听到对象、数组的变化
      handler (newV, oldV) {
        this.initDate()
      },
      deep: true
    }
  }
}
</script>

<style lang="scss">
.custom-video-progress {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  .el-progress-bar__outer {
    background: rgba(133, 133, 133, 0.6)!important;
  }
  .el-progress-bar__inner {
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    background-color: #409EFF;
    text-align: right;
    border-radius: 100px;
    line-height: 1;
    white-space: nowrap;
  }
}
@keyframes progressAnimation {
  from {
    width: 0;
  }
  to {
    width: 740px;
  }
}
</style>
